package com.toocms.jinjuhang.ui.index.news

import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import android.view.View
import com.google.android.material.tabs.TabLayout
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.databinding.FgtNewsBinding
import com.toocms.jinjuhang.ui.base.BaseFgt
import com.toocms.tab.TooCMSApplication

class NewsFgt : BaseFgt<FgtNewsBinding, NewsModel>() {
    override fun onFragmentCreated() {
        topBar.setTitle(
            when (arguments?.get(Constants.BundleKey.KEY_TYPE)) {
                Constants.Extra.NEWS_TYPE_NEWS -> R.string.str_news
                Constants.Extra.NEWS_TYPE_ACTIVE -> R.string.str_active
                else -> R.string.str_news
            }
        )
        binding.filterTl.apply {
            addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    tab?.apply {
                        val spannableStringBuilder = SpannableStringBuilder(text.toString())
                        spannableStringBuilder.setSpan(
                            RelativeSizeSpan(1.2f),
                            0,
                            spannableStringBuilder.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        text = spannableStringBuilder
                        viewModel.cateId = tag.toString()
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                    tab?.apply {
                        text = text.toString()
                    }
                }

            })
        }
    }

    override fun getLayoutResId() = R.layout.fgt_news

    override fun getVariableId() = BR.newsModel

    override fun viewObserver() {
        viewModel.filtersSingleLiveEvent.observe(this) { filters ->
            binding.filterTl.visibility = if (1 >= filters.size) View.GONE else View.VISIBLE
            filters.forEach {
                val tab = binding.filterTl.newTab().setText(it.name).setTag(it.id)
                binding.filterTl.addTab(tab)
            }
        }
        viewModel.stopRefreshOrLoadSingleLiveEvent.observe(this) {
            binding.refreshSrl.finishRefresh()
            binding.refreshSrl.finishLoadMore()
        }
    }

    override fun getViewModel() = NewsModel(TooCMSApplication.getInstance(), arguments)
}